package com.neurotech.pcc.vm

import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import com.neurotech.pcc.dummy.RemoteDao
import com.neurotech.pcc.dummy.RemoteModel
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

/**
 * Created by shenhua on 2018/10/15.
 * @author shenhua
 *         Email shenhuanet@126.com
 */
class RemotesRepository private constructor(private val remoteDao: RemoteDao) {

    private val threadPoolExecutor = ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, LinkedBlockingQueue<Runnable>())

    companion object {
        @Volatile
        private var instance: RemotesRepository? = null

        fun dao(remoteDao: RemoteDao) =
                instance ?: synchronized(this) {
                    instance ?: RemotesRepository(remoteDao).also { instance = it }
                }
    }

    fun getRemotes() = remoteDao.getAllRemotes()

    fun insert(remoteModel: RemoteModel) {
        threadPoolExecutor.execute {
            remoteDao.insertRemotes(remoteModel)
        }
    }

    fun delete(remoteModel: RemoteModel) {
        threadPoolExecutor.execute {
            remoteDao.deleteRemotes(remoteModel.id!!)
        }
    }

    fun update(remoteModel: RemoteModel) {
        threadPoolExecutor.execute {
            remoteDao.updateRemote(remoteModel)
        }
    }
}

@Suppress("UNCHECKED_CAST")
class RemotesRepositoryFactory(
        private val repository: RemotesRepository
) : ViewModelProvider.NewInstanceFactory() {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        return RemotesViewModel(repository) as T
    }
}